package Utility;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUtilities{     

    /**
     *  This method accepts PATHNAME and FILENAME as arguments - which creates file with FILENAME under PATHNAME (Absolute PathName)
     * @param path
     * @param filename
     * @throws IOException
     */
    public static void createFile(String path, String filename) throws IOException
    {
        String pathname = path;
        String fname = filename;
        String file = pathname.concat(fname);
        File f = new File(file);
        if(f.exists())
        {
            System.out.println("File already exists " + fname);
        }
        else
        {
            f.createNewFile();
            System.out.println("new file:- " + fname + " created at:- " + pathname);
        }
    }

    /**
     * This method takes absolute pathname and directory name as input - this creates a directory under specified pathname
     * @param path
     * @param directoryName
     */
    public static void createDirectory(String path, String directoryName)
    {
        String pathname = path;
        String dirname = directoryName;
        String pname = pathname.concat(dirname);
        boolean pass;
        pass = new File(pname).mkdir();
        if(pass)
        {
            System.out.println("Directory successfully created: " + dirname + " at path " + pathname);
        }
        else
        {
            System.out.println("Directory at path " +pathname+ " couldnt be created ");

        }
    }   
    /**
     * This program takes single line of text and writes in the file specified.
     * This is especially used by the ChunkServers to perform Write operations on chunks.
     *
     * @param text
     */
    public static void writeToLoadFile(String filename,String text) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename), false));
            bw.write(text);
            bw.newLine();
            bw.close();
        } catch (Exception e) {
        }
    }
   
    /**
     * This program takes single line of text and writes in the file specified.
     * This is especially used by the ChunkServers to perform Write operations on chunks.
     *
     * @param text
     */
    public static void writeToFile(String filename,String text,boolean append) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(new File(filename), append));
            bw.write(text);
            bw.newLine();
            bw.close();
        } catch (Exception e) {
        }
    }

    /**
     * This method returns all the files with starting with filename given present in the folder or directory given.
     */

    public static List<String> getAllFilesMatchingFileName(String directory,String fileName){
        List<String> files = new ArrayList<String>();
        String fileNameAsString;
        File folder = new File(directory);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++)
        {
            if (listOfFiles[i].isFile())
            {
                fileNameAsString = listOfFiles[i].getName();
                if (fileNameAsString.contains(fileName))
                {
                    //System.out.println(fileNameAsString); // Just to List all the versions of the file availbale in the folder.
                    files.add(fileNameAsString);
                }
            }
        }
        return files;
    }
    /**
     * This method returns all the files with starting with filename given present in the folder or directory given.
     */

    public static boolean doesFileExist(String directory,String fileName){
        boolean isFilePresent = false;
        String fileNameAsString;
        File folder = new File(directory);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i++)
        {
            if (listOfFiles[i].isFile())
            {
                fileNameAsString = listOfFiles[i].getName();
                if (fileNameAsString.contains(fileName))
                {
                    isFilePresent = true;
                }
            }
        }
        return isFilePresent;
    }
    /**
     * This creates a new file taking absolute path name
     * @param pathName
     * @return
     * @throws IOException
     */
    public static boolean createFile(String pathName) throws IOException{
        File f = new File(pathName);
              return f.createNewFile();
    }
   
/**
 * This method returns the file content as String
 */
    public static String readFileAsString(String filePath) throws java.io.IOException{
        byte[] buffer = new byte[(int) new File(filePath).length()];
        BufferedInputStream f = null;
        try {
            f = new BufferedInputStream(new FileInputStream(filePath));
            f.read(buffer);
        } finally {
            if (f != null) try { f.close(); } catch (IOException ignored) { }
        }
        return new String(buffer);
    }
   
    /**
     * Read the file and return the map<lock,client>
     */
    public synchronized HashMap<Integer,String> readFileAsMap(String filePath){
    	HashMap<Integer,String> myMap = new HashMap<Integer,String>();
    	try {
			BufferedReader br = new BufferedReader(new FileReader(filePath));
			String line = null;
			while((line = br.readLine())!=null){
				String[] stringContent = line.split(",");
				myMap.put(Integer.parseInt(stringContent[0]),stringContent[1].trim());
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return myMap;
    }
   
}